﻿using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Text;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal struct LPWideString 
    {
        private string _value;
        // private byte[] bytes;

        public void Read(BinaryReader reader)
        {
#if DEBUG
            var pos = reader.BaseStream.Position;
#endif
            ushort cchCharacters = reader.ReadUInt16();
            var bytes = reader.ReadBytes(cchCharacters*2);
            this._value = Utf16Encoding.GetString(bytes);
#if DEBUG
            Contract.Assert(reader.BaseStream.Position == pos + ByteCount);
#endif
        }

        private static Encoding Utf16Encoding { get { return XlEncodings.TwoByteEncoding; } }

        internal int ByteCount
        {
            get { return 2 + _value.Length*2; }
        }

        public void Write(BinaryWriter writer)
        {
            writer.Write((ushort)(_value.Length));
            // writer.Write(bytes);
            byte[] bytes = Utf16Encoding.GetBytes(_value);
            writer.Write(bytes);
        }
    }
}